<?php

namespace App\Jobs;

use App\Exceptions\ApiException;
use App\Models\ClientUserIntegral;
use App\Models\ClientUserManagerDuty;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

/**
 * Class ManagerDuty
 * @package App\Jobs
 * 管理人员值班监听
 */
class ManagerDuty implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
		
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
		$now_time = time();
		$date = date('Y-m-d',$now_time);
		$date2 = date('Y-m-d H:i:s',$now_time);
		// 找到在值班的人
		$duty = ClientUserManagerDuty::where(['status'=>1])->get();
		$duty->each(function($v,$k) use ($date,$date2,$now_time){
			
			$date_unix = strtotime($v->date)+86399;
			//  当前时间大于记录的时间 说明到第二天了 
			if($now_time > $date_unix){
				$save = []; // 需要更新的数据
				$save['status'] = 0; // 更新原记录的状态为已经结束
				$save['updated_at'] = $date2;
				$save['end_time'] = $now_time;
				ClientUserManagerDuty::where(['uid'=>$v->uid,'status'=>1])->update($save);
				// 添加一条新记录
				$create = [
					'uid'		=> $v->uid,
					'date'		=> $date,
					'start_time'=> $now_time,
					'created_at'=> $date2,
					'status'	=> 1,
				];
				ClientUserManagerDuty::create($create)->id;
				// 如果今日开始时间和结束时间超过8小时视为完成值班，赠送积分
				// if(!$v->integral && ($v->start_time - $v->end_time) / 3600 >= 8){
				// 	$clientUserIntegral = ClientUserIntegral::create()->data($v->uid,2);
				// 	$clientUserIntegral->save();
				// 	$save['integral'] = $clientUserIntegral->integral;
				// }
			}
			
		});
		return true;
    }
	
	public function failed($exception = null)
	{
		send_mail('512511253@qq.com','【慧城】值班监听队列失败');
	}
}
